﻿using CQIE.JonJack.Models;
using CQIE.JonJack.Models.Tabels;
using CQIE.JonJack.SplLibraryService._IReaderService;
using CQIE.JonJack.UtilitySource;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Polly;
using Polly.Fallback;
using Polly.Timeout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CQIE.JonJack.SplLibraryService.ReaderServiceImpl
{
    public class ReaderServiceImpl : IReaderService
    {
        private readonly _DbContext Db;
        private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;
        private IDistributedCache RedisCache;
        private readonly PollyServices pollyServices;
        private Policy<string> _policy;
        private AsyncTimeoutPolicy policy;
        private Policy<string> fallBackPolicy;
        private Policy<string> wrapPolicy;
        private Policy<string> circuiBreaker;


        public ReaderServiceImpl(_DbContext db, IOptionsSnapshot<JWTSettings> jwtSettingsOpt, IDistributedCache redisCache, PollyServices pollyServices)
        {
            Db = db;
            this.jwtSettingsOpt = jwtSettingsOpt;

            RedisCache = redisCache;
            this.pollyServices = pollyServices;

            //执行polly操作
            //pollyServices.TestCircuitBreaker();
            //降级
            _policy = pollyServices.TestRetry2();//重试
            policy = pollyServices.TestTimeOut();//超时
            fallBackPolicy = pollyServices.TestFallback();//回退
            wrapPolicy = pollyServices.TestWrapPolicy();//组合策略
            circuiBreaker = pollyServices.TestWrapPolicy_2();//熔断降级
        }

        public bool changePassWord(string uid, string jsonStirng)
        {
            circuiBreaker.Execute(() =>
            {
                User user = Db.User.Where(u => u.SchoolNumber == uid).Single();
                // 反序列化JSON字符串为匿名对象
                var jsonUser = JsonConvert.DeserializeObject<dynamic>(jsonStirng);
                string op = jsonUser!.oldPassword;
                string np = jsonUser.newPassword;
                if (user.PassWord == op)
                {
                    user.PassWord = np;
                }
                Db.SaveChanges();
                return "Operation completed successfully.";
            });

            
            return true;
        }

        public bool changePersonInfo(string uid, string jsonStirng)
        {
            circuiBreaker.Execute(() =>
            {
                User user = Db.User.Where(u => u.SchoolNumber == uid).Single();
                // 反序列化JSON字符串为匿名对象
                var jsonUser = JsonConvert.DeserializeObject<dynamic>(jsonStirng);

                user.SchoolNumber = jsonUser.schoolNumber;
                user.Name = jsonUser.name;

                Db.SaveChanges();
                return "Operation completed successfully.";
            });

            
            return true;
        }

        public string getUserInfo(string uid)
        {
            string jsonString = "";

            circuiBreaker.Execute(() =>
            {
                User user = Db.User.Where(u => u.SchoolNumber == uid).Single();
                var jsResult = new
                {
                    name = user.Name,//用户名
                    schoolNumber = user.SchoolNumber,//学号
                };

                jsonString = JsonConvert.SerializeObject(jsResult);
                return "Operation completed successfully.";
            });

            
            return jsonString;
        }
    }
}
